import * as hx from "hbuilderx";
import { CountInfo } from "./type";
import { getExt } from "./common"
import notifier from "./notifier";

type ExtCountInfo = Omit<CountInfo, "filePath"> & {
    ext: string,
    fileCount:number,
    files:CountInfo[]
}

class DialogCallbackObject {
    copyToClipBoard(text: string): Promise<string> {
        // console.log("copyed", text);
        return new Promise((resolve,reject) => {
            hx.env.clipboard.writeText(text).then(() => {
                hx.window.showToast({ message: "详细信息已复制到剪切板√√√" });
                resolve(text);
            }).catch(reject);
        });
    }
    gotoSetting() {
        hx.workspace.gotoConfiguration('count.file.lines.1.filters.non.suffix')
    }
    addToFilter(ext: string) {
        if (!ext) {
            return;
        }
        const newFilterForExt = `${ext.replace(/\./g, "\\.")}$`;

        const config = hx.workspace.getConfiguration();
        let applyText = newFilterForExt;

        const ignoreCFG = (config.get("count.file.lines.4.filters.ignore", "") as string);
        if (ignoreCFG) {
            const filters = ignoreCFG.split(";").map(f => f.trim());
            if (filters.includes(newFilterForExt)) {
                hx.window.showToast({ message: "已经存在此文件类型忽略<font style=\"background:yellow\">!!!</font>" });
                return
            }

            filters.push(newFilterForExt);
            applyText = filters.join(";");
        }

        console.log("applyText", applyText);
        config.update("count.file.lines.4.filters.ignore", applyText).then(() => {
            hx.window.showToast({ message: "已添加到配置<font style=\"background:lightgreen\">√√√</font>" });
        });
    }
    addToMatch(ext: string) {
        if (!ext) {
            return;
        }
        const newMatchForExt = `^[^.]*${ext.replace(/\./g, "\\.")}$`;

        const config = hx.workspace.getConfiguration();
        let applyText = newMatchForExt;

        const matchCFG = (config.get("count.file.lines.6.filters.match", "") as string);
        if (matchCFG) {
            const filters = matchCFG.split(";").map(f => f.trim());
            if (filters.includes(newMatchForExt)) {
                hx.window.showToast({ message: "已经存在此文件类型匹配<font style=\"background:yellow\">!!!</font>" });
                return
            }

            filters.push(newMatchForExt);
            applyText = filters.join(";");
        }

        console.log("applyText", applyText);
        config.update("count.file.lines.6.filters.match", applyText).then(() => {
            hx.window.showToast({ message: "已添加到配置<font style=\"background:lightgreen\">√√√</font>" });
        });
    }
    showQuestion(msg: string): Promise<boolean> {
        return new Promise((resolve, _) => {
            let result = hx.window.showMessageBox({
                type: 'question',
                title: '',
                text: msg,
                buttons: ['确定', '取消']
            });
            result.then((button: string) => {
                return resolve(button == '确定')
            });
        });
    }
    openFileEditor(filePath: string | { content: string, language: string }): Promise<any> {
        return hx.workspace.openTextDocument(filePath);
    }
    cleanFilterAndMatch() {
        const config = hx.workspace.getConfiguration();
        config.update("count.file.lines.4.filters.ignore", "");
        config.update("count.file.lines.6.filters.match", "");
    }
}

export class Displayer {
    constructor(private startTime: number, private fileName: string, private countInfos: CountInfo[]) { }

    async display(): Promise<0 /* normal */ | 1 /* recount */> {
        const config = hx.workspace.getConfiguration()
        const ignoreCaseCFG = config.get("count.file.lines.7.filters.suffix.ignoreCase",false) as boolean;
        
        const cache: Map<string /**/, ExtCountInfo> = new Map;

        for (let countInfo of this.countInfos) {
            const ext = ignoreCaseCFG ? getExt(countInfo.filePath).toLowerCase() : getExt(countInfo.filePath);
            if (!cache.has(ext)) {
                cache.set(ext, {
                    ext,
                    fileCount:0,
                    count: 0,
                    emptyCount: 0,
                    annotationCount: 0,
                    files:[]
                })
            }
            const extInfo: ExtCountInfo = cache.get(ext)!;
            extInfo.fileCount++;
            extInfo.count += countInfo.count;
            extInfo.emptyCount += countInfo.emptyCount;
            extInfo.annotationCount += countInfo.annotationCount;
            extInfo.files.push(countInfo);
        }
        notifier.readAll();
        const result = await hx.window.showFormDialog({
            title: "统计文件代码行",
            customButtons: [
                {
                    "text": "重新统计"
                },
                {
                    "text": "关闭",
                    "role": "accept"
                }
            ],
            showModal: false,
            width: 1000,
            height: 600,
            validate: async function (formData: any) {
                return true;
            },
            formItems: [
                {
                    type: "vue:fileLinesCounterDisplayer",
                    name: "fileLinesCounterDisplayer",
                    value: {
                        fileName: this.fileName,
                        countInfos: this.countInfos,
                        washedInfos: cache,
                        startTime: this.startTime,
                        dialogCallbackObject: new DialogCallbackObject()
                    }
                },
            ],
        });
        return result.buttonIndex == 0 ? 1 : 0
    }
}